<?php
/**
 * this class is responsible for creating a properly formed User model with all it's 
 * dependencies. 
 *
 */
class user_UserRepository
{
	/**
	 * holds a reference to the userMapper class that will be in charge of interacting
	 * with the DB
	 *
	 * @var user_UserMapper
	 */
	protected $userMap;
	
	
	public function __construct()
	{
		$this->userMap = new user_UserMapper();
		$this->profileMap = new profile_ProfileMapper();
	}
	
	/**
	 * this method returns a clean user object instantiated in the appropriate way
	 *
	 */
	public function getNewUser()
	{
		$user = new user_User();
		$profile = new profile_Profile();
		$user->setProfile($profile);
		return $user;
	}
	
	
	public function find($id)
	{
		// check to see if the user obj is already in the cache
		$user = ObjectManager::exists('user_User', $id);
		if(!$user) {
			// user is not in identity map cache, create new one and add to cache
			$user = $this->userMap->find($id);
			$user->setProfile($this->profileMap->findByUser($user));
			ObjectManager::addToMap($user);
		}
		return $user;
	}
	
	/**
	 * the save method does the job of determining if we need to update this object or create a new one
	 *
	 * @param user_User $user
	 */
	public function save(user_User $user)
	{
		if(is_null($user->getId())) {
			// create a new user since we didn't have an id
			$userId = $this->userMap->create($user);
			$user->Profile->setUserId($userId);
			$this->profileMap->create($user->Profile);
		} else {
			$this->userMap->save($user);
			$this->profileMap->save($user->Profile);
		}
		
	}
}